<template>
  <Modal v-model="visible"
         title="修改密码"
         @on-cancel="closeModal"
         footer-hide
         :width="480">
    <Form ref="form" :model="form" :rules="rules"
          :label-width="100">
      <FormItem label="新密码" prop="password">
        <Input v-model="form.password" type="password"
               placeholder="请输入新密码"></Input>
      </FormItem>
      <FormItem label="确认密码" prop="confirmPassword">
        <Input v-model="form.confirmPassword" type="password"
               placeholder="请输入确认密码"></Input>
      </FormItem>
      <FormItem>
        <Button type="primary" :loading="submitting" @click="submit">提交</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script>
import { updatePassword } from '../../../../apis/system/user';

export default {
  name: 'updatePassword',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (this.form.confirmPassword && this.form.confirmPassword !== '') {
        // 对第二个密码框单独验证
        this.$refs.form.validateField('confirmPassword');
      }
      callback();
    };
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('确认密码与新密码不一致'));
        return;
      }
      callback();
    };

    return {
      visible: false,
      id: '',
      form: {
        password: undefined,
        confirmPassword: undefined
      },
      rules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码至少6位', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
      },
      submitting: false
    };
  },
  methods: {
    openModal(id) {
      this.$refs.form.resetFields();
      this.visible = true;
      this.id = id;
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitting = true;

          updatePassword(this.id, {
            password: this.form.password
          }, () => {
            this.submitting = false;

            this.$Message.success('保存成功');
            this.closeModal();
            this.$refs.form.resetFields();
            this.$emit('success');
          }, () => {
            this.submitting = false;
          });
        }
      });
    },
    closeModal() {
      this.visible = false;
    }
  }
};
</script>

<style scoped>

</style>
